"""Command line utilities"""

import subprocess
from typing import List, Tuple

from loguru import logger


def execute_command(
    command, console_output: bool = True, **kwargs
) -> Tuple[List[str], List[str]]:
    """Execute a command and returns the output lines of stdout and stderr as lists"""

    def print_console_output(output_lines, other_lines):
        if console_output:
            for line in output_lines:
                line = line.strip()
                if line:
                    logger.info(line)
            for line in other_lines:
                line = line.strip()
                if line:
                    logger.warning(line)

    try:
        info = f"Executing command: {command}"
        if "cwd" in kwargs:
            cwd = kwargs["cwd"]
            info += f", cwd: {cwd}"
        logger.info(info)

        # Using subprocess.run to execute the command
        result = subprocess.run(
            command,
            shell=True,  # Run the command in a shell
            check=True,  # If the command fails, raise an exception
            text=True,  # Return the output as text
            capture_output=True,  # Capture the output of the command
            **kwargs,
        )

        # Split the output into lines
        output_lines = result.stdout.splitlines()
        # Split the error output into lines
        error_lines = result.stderr.splitlines()
        print_console_output(output_lines, error_lines)
        return output_lines, error_lines
    except subprocess.CalledProcessError as e:
        logger.critical(
            f"Command execution failed: `{e}`\nConsole output:\n {e.output}"
        )
        # Return an empty list for output_lines
        output_lines = []
        error_lines = e.output.splitlines()
        return output_lines, error_lines
